#include "servlistwidget.h"

ServListWidget::ServListWidget(QWidget *parent) :
    QWidget(parent) {

    list = new QListWidget();

    hostGame_b = new QPushButton("Host game");
    refreshList_b = new QPushButton("Refresh list");
    connect_b = new QPushButton("Connect");
    connetByIp_b = new QPushButton("Connect by IP");

    lineEdit = new QLineEdit();
    lineEdit->setMaxLength(18);
    lineEdit->setText("WorldEdit");

    ipEdit = new QLineEdit();
    ipEdit->setMaxLength(15);
    ipEdit->setText("172.168.13.14");

    QHBoxLayout* connectBar = new QHBoxLayout();
    connectBar->addStretch(1);
    connectBar->addWidget(ipEdit);
    connectBar->addWidget(connetByIp_b);

    QHBoxLayout* hLayout = new QHBoxLayout();
    hLayout->addWidget(hostGame_b);
    hLayout->addStretch(1);
    hLayout->addWidget(refreshList_b);
    hLayout->addWidget(connect_b);

    QWidget* buttons= new QWidget();
    buttons->setLayout(hLayout);

    QWidget* strConnect = new QWidget();
    strConnect->setLayout(connectBar);

    QVBoxLayout* vLayout = new QVBoxLayout();
    vLayout->addWidget(new QLabel("Name:"));
    vLayout->addWidget(lineEdit);
    vLayout->addWidget(strConnect);
    vLayout->addWidget(new QLabel("Games:"));
    vLayout->addWidget(list);
    vLayout->addWidget(buttons);

    setLayout(vLayout);

    list->setStyleSheet("* {background-image: url(./tankbg.jpg)}");

    connect(connect_b, SIGNAL(clicked(bool)), this, SLOT(tryToConnect()));

}

void ServListWidget::redrawList(std::vector<Host> *hosts) {

    list->clear();

    if (hosts == NULL)
        return;

    QString line;
    QString num;
    Host* host;

    servList = hosts[0];

    for (std::vector<Host>::iterator it = hosts->begin(); it != hosts->end(); it++) {

        line = "";
        host = &(*it);

        line += host->name;
        line += " [";

        line += QString::fromStdString(host->ip.toString());
        line += "] ";

        num.setNum(host->plCount, 10);
        line += num;
        line += "/10";

        list->addItem(line);
    }

    //msg = '[' + QTime::currentTime().toString() + "]: " + str;
    //item(count()-1)->setForeground(brush);
}

void ServListWidget::tryToConnect() {

    if (list->selectedItems().size() != 1)
        return;

    emit connectTry((servList[list->currentRow()]).ip);
}
